import { WL_NotificationType, WeilaCore } from "weilasdk_lite";
import { WeilaMiniNetwork } from "@/miniprogram/utils/weila_mini_network";
import { WeilaMiniStorage } from "@/miniprogram/utils/weila_mini_storage";

/**
 * 格式化日期
 * @param date 日期对象
 * @param format 格式化模板
 * @returns 格式化后的字符串
 */
export function formatDate(date: Date, format: string): string {
  const o: Record<string, number> = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'h+': date.getHours() % 12 || 12,
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  };

  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }

  for (const k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(
        RegExp.$1, 
        RegExp.$1.length === 1 ? String(o[k]) : ('00' + o[k]).substr(('' + o[k]).length)
      );
    }
  }
  return format;
}


export function register_weila_notification_handler(weilaCore: WeilaCore, eventEmitter: any): void {
  weilaCore.weila_listenNotification((event: number, eventData: any) => {
    switch (event) {
      case WL_NotificationType.SESSION_MSG_NOTIFICATION: {
        eventEmitter.emit("session_msg", eventData);
      }
      break;
    }
  });
}


export function get_weilaCore(app: any): WeilaCore {
  if (!app.globalData.weilaCore) {
    app.globalData.weilaCore = new WeilaCore();
    app.globalData.weilaCore.weila_init(new WeilaMiniNetwork(), new WeilaMiniStorage());
  }
  return app.globalData.weilaCore;
}